<template>

  <HeaderNav/>
  <article>
    <div id="main">
      <section class="ct">
        <div class="upload">
          <h1>账号绑定<em><a class="bind" @click="gotoRegister">如果没有账号，请点击注册</a></em></h1>

          <form action="/third/bind" autocomplete="off" id="myform" method="post">
            <p>
              <label>手机号：</label>
              <input class="upt" type="text" name="tel" placeholder="请输入手机号" v-model.trim="tel"/>
              <em></em>
            </p>
            <p>
              <label>密码：</label>
              <input class="upt" type="password" name="password" v-model.trim="password" placeholder="请输入密码"/>
              <em></em>
            </p>
            <p>
              <label class="btn bind">
                <a class="btn" @click="handleBind">确认绑定</a>
              </label>
            </p>

          </form>
        </div>
      </section>
    </div>
  </article>
  <Footer/>
</template>

<script setup>
import HeaderNav from "../components/HeaderNav.vue";
import Footer from "../components/Footer.vue";
import {ref} from 'vue' ;
import toastr from 'toastr'
import API from '../api/index.js'

import {useRoute, useRouter } from 'vue-router' ;
import store from "../store";

const route = useRoute();
const router = useRouter();

const tel = ref("");
const password = ref("");

function handleBind() {
  if (tel.value == "") {
    toastr.error("手机号不允许为空");
    return;
  }

  if (!/^1[3-9]\d{9}$/.test(tel.value)) {
    toastr.error("手机号格式不正确");
    return;
  }

  if (password.value == "") {
    toastr.error("密码不允许为空");
    return;
  }
  // 进行数据绑定
  API.bindAccount({...route.query, tel: tel.value, password: password.value}).then(ret => {
    if (ret.status) {
      let rememberMe = atob(route.query.state);
      store.commit("storeUserAndToken", {
        user: ret.data.user, token: ret.data.accessToken, exp: ret.data.exp,
        refresh: ret.data.refreshToken, remember: rememberMe === "on" ? true : false
      });
      // 登录成功、跳转到系统首页
      router.push("/");
    }

  })
}
// 当没有账号，跳转到注册页面（该怎么做？？）
function gotoRegister() {
   router.push({name: "register" , query: route.query })
}

</script>

<style scoped>

</style>